package com.shetuan.servelt;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shetuan.bean.Login;
import com.shetuan.bean.Member;
import com.shetuan.dao.LoginDao;
import com.shetuan.dao.MemberDao;

public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String log = request.getParameter("log");
        request.getSession().setAttribute("log", log);

        LoginDao logindao = new LoginDao();

        String username = request.getParameter("username");
        String userpass = request.getParameter("userpass");

        Login login = logindao.login(username, userpass);

        if (login == null) {
            if (log.equals("log")) {
                request.setAttribute("error", "uname");
                request.getRequestDispatcher("login.jsp").forward(request, response);
                return;
            } else if (log.equals("admin")) {
                request.setAttribute("error", "uname");
                request.getRequestDispatcher("admin_login.jsp").forward(request, response);
                return;
            }
        } else {
            if (log.equals("log")) {
                request.getSession().setAttribute("msg", 2);
                request.getSession().setAttribute("login", login);
                response.sendRedirect("index2.jsp");
                return;
            } else if (log.equals("admin")) {

                int managerId = login.getManagerId();

                if (managerId == 1 || managerId == 2) {
                    request.getSession().setAttribute("login", login);
                    response.sendRedirect("admin");
                    return;
                } else {
                    request.setAttribute("error", "notadmin");
                    request.getRequestDispatcher("admin_login.jsp").forward(request, response);
                    return;
                }
            }
        }
    }
}